﻿using System.Collections.Generic;
using UnityEngine;
using WebSocketSharp;
using System;
using LitJson;

using VFramework;

namespace VFramework
{
	/// <summary>
	/// 与机器驱动通信的控制器
	/// 建立一个websocket与机器通信
	/// </summary>
	public class MController
	{

		private string host = "ws://127.0.0.1:10086";

		private static MController _instance = null;
		private WebSocket webSocket = null;




		private MController ()
		{

		}




		public void connect ()
		{
#if UNITY_STANDALONE_LINUX
			if (webSocket == null || webSocket.ReadyState != WebSocketState.Open) { //这些状态不对..
				webSocket = new WebSocket (host);
				webSocket.OnOpen += delegate (object sender, EventArgs e) {
					VLogger.debug (" connection made !! , status = " + webSocket.ReadyState);
				};
				webSocket.OnError += delegate (object sender, ErrorEventArgs e) {
					VLogger.debug ("error " + e.Message);
				};
				webSocket.OnClose += delegate (object sender, CloseEventArgs e) {
					VLogger.debug ("close code=" + e.Code + ", reason = " + e.Reason);
				};

				VLogger.debug ("---- start connect ---" + host);

				webSocket.OnMessage += delegate (object sender, MessageEventArgs e) {
					if (e.IsPing) {

					} else {
						try {
							MachineObject.pushMachineMsg (JsonMapper.ToObject (e.Data));
						} catch (Exception exception) {
							VLogger.error (exception.ToString ());
						}
					}
				};
				webSocket.Connect ();
			}
#else
			webSocket = null;
#endif
		}

		public void sendCmd (MachineCmd cmd)
		{
			try {
				connect ();
				if (webSocket == null) {
					return;
				}

				if (webSocket.ReadyState == WebSocketState.Open) {
					MachineObject.pushTmpCallback (cmd.getCmd (), cmd);
					webSocket.Send (cmd.toMsg ());
				}

			} catch (Exception e) {
				VLogger.debug ("sendCmd error" + e.Message);
			}
		}

		public WebSocket getWebSocket ()
		{
			return webSocket;
		}

		void init ()
		{

		}


		public void release ()
		{
			try {
				if (webSocket != null) {
					webSocket.Close ();
				}
				MachineObject.release ();
			} catch (System.Exception e) {
				VLogger.error (e.ToString ());
			}
		}
		public static MController g ()
		{
			if (_instance == null) {
				_instance = new MController ();
				_instance.init ();
			}
			return _instance;
		}
	}
}